import { reactive, watch } from 'vue';

const noop: any = () => {}

interface MethodsOpt {
  getData: Function // 获取表格数据方法
}

interface TableState {
  // 表格数据
  loading: boolean;
  data: Array<any>;
  // 分页器
  current: number;
  size: number;
  total: number;
}

export const useTableHook = function(methodsOpt: MethodsOpt) {
  const tableState = reactive<TableState>({
    loading: false,
    data: [],
    current: 1,
    size: 10,
    total: 0,
  });

  const tableMethods = {
    // 数据获取
    getData: methodsOpt && methodsOpt.getData || noop,
    // 搜索，页码重置
    getSearchData() {
      if (tableState.current !== 1) {
        tableState.current = 1;
      } else {
        tableMethods.getData();
      }
    },
    // 当成功删除若干条条数据后调该方法，进行智能分页判断
    getDelData(delNumber = 1) {
      const oldCurrent = tableState.current
      // 计算出临界点
      tableState.current =
        tableState.total % tableState.size === delNumber || tableState.size === 1
        ? 
        tableState.current > 1
          ? tableState.current - 1
          : tableState.current
        : 
        tableState.current;
      if (tableState.current === oldCurrent) {
        tableMethods.getData(); 
      }
    },
    // 清空数据
    clearData() {
      tableState.data = []
      tableState.total = 0
    }
  };
  
  watch(
    () => tableState.current,
    () => {
      tableMethods.getData()
    }
  )

  watch(
    () => tableState.size,
    () => {
      if (tableState.current === 1) {
        tableMethods.getData()
      } else {
        tableState.current = 1
      }
    }
  )

  return {
    tableState,
    tableMethods
  }
}
